/**
 *
 *  CheckArticleUserFilter.cc
 *
 */

#include "CheckArticleUserFilter.h"

using namespace drogon;
using namespace drogon::orm;

void CheckArticleUserFilter::doFilter(const HttpRequestPtr& req,
                                      FilterCallback&&      fcb,
                                      FilterChainCallback&& fccb)
{
    auto jsonPtr = req->jsonObject();
    if (!jsonPtr) {
        Json::Value ret;
        ret["error"] = "No json object is found in the request";
        auto resp    = HttpResponse::newHttpJsonResponse(ret);
        resp->setStatusCode(k400BadRequest);
        fcb(resp);
        return;
    }

    if (!jsonPtr->isMember("article_id") || !jsonPtr->isMember("user_id")) {
        Json::Value ret;
        ret["error"] = "请求格式错误!!!";
        auto resp    = HttpResponse::newHttpJsonResponse(ret);
        resp->setStatusCode(k400BadRequest);
        fcb(resp);
        return;
    }

    auto requestUserId    = (*jsonPtr)["user_id"].asString();
    auto requestArticleId = (*jsonPtr)["article_id"].asString();

    auto dbClientPtr = getDbClient();

    drogon::orm::Mapper<Article> mapper(dbClientPtr);

    mapper.findByPrimaryKey(
        std::stoi(requestArticleId), 
        [fcb, fccb, requestUserId](Article r) {
            auto resultArticleId = r.getOwnerUserId();
            if (std::to_string(*resultArticleId).compare(requestUserId) !=
                0) {
                Json::Value ret;
                ret["error"] = "非法请求";
                auto resp    = HttpResponse::newHttpJsonResponse(ret);
                resp->setStatusCode(k400BadRequest);
                fcb(resp);
                return;
            }
            fccb();
        },
        [fcb](const DrogonDbException& e) {
            const drogon::orm::UnexpectedRows* s =
                dynamic_cast<const drogon::orm::UnexpectedRows*>(&e.base());
            if (s) {
                auto resp = HttpResponse::newHttpResponse();
                resp->setStatusCode(k404NotFound);
                fcb(resp);
                return;
            }
            LOG_ERROR << e.base().what();
            Json::Value ret;
            ret["error"] = "database error";
            auto resp    = HttpResponse::newHttpJsonResponse(ret);
            resp->setStatusCode(k500InternalServerError);
            fcb(resp);
        });
}
